import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker/date_picker.dart';
import 'package:flutter_cupertino_date_picker/date_picker_i18n.dart';
import 'package:flutter_cupertino_date_picker/date_picker_theme.dart';
import 'package:flutter_picker/Picker.dart';
import 'package:image_picker/image_picker.dart';
import 'package:wanchong/api/pet.dart';
import 'package:wanchong/app/perinfor/nick.dart';
import 'package:wanchong/app/perinfor/petdevice.dart';
import 'package:wanchong/app/pet/add.dart';
import 'package:wanchong/bean/pet_info_entity.dart';
import 'package:wanchong/bean/success_entity.dart';
import 'package:wanchong/conf.dart';
import 'package:wanchong/utils/event_bus.dart';
import 'package:wanchong/utils/upload.dart';
import 'package:wanchong/widget/app_bar.dart';
import 'package:wanchong/path.dart';
import 'package:wanchong/widget/loading.dart';
// import 'package:intl/intl.dart';

class PetInfo extends StatefulWidget {
  final int id;

  PetInfo({Key key, @required this.id}) : super(key: key) {
    print(this.id);
  }

  @override
  _UserInfoState createState() => _UserInfoState();
}

class _UserInfoState extends State<PetInfo> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  String _format = 'yyyy-MMMM-dd';
  PetInfoEntity petInfoEntity;
  bool finished = false;
  @override
  void initState() {
    getPetInfo(widget.id.toString()).listen((PetInfoEntity data) {
      // print(data);
      petInfoEntity = data;
      setState(() {
        finished = true;
      });
    }).onError((e) {
      print(e);
    });
    // print(widget.id);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return !finished
        ? Loading()
        : Scaffold(
            key: _scaffoldKey,
            appBar: MyAppBar(
                child: Align(
              //alignment: Alignment.center,
              child: Container(
                padding: EdgeInsets.only(left: 10.0, right: 10.0),
                child: Stack(
                  children: <Widget>[
                    GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                      },
                      child: new Align(
                        alignment: FractionalOffset.centerLeft,
                        child: Container(
                          padding: EdgeInsets.only(right: 15.0),
                          color: Colors.transparent,
                          height: double.infinity,
                          child:
                              Image.asset("assets/login/top_return_icon.png"),
                        ),
                      ),
                    ),
                    new Align(
                      alignment: FractionalOffset.center,
                      child: new Text(
                        '宠物信息',
                        style: new TextStyle(
                          color: Color(0xFF3C4450),
                          fontSize: 15.0,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            )),
            body: Container(
              height: double.infinity,
              child: Column(
                children: <Widget>[
                  Expanded(
                    child: Container(
                      child: ListView(
                        physics: BouncingScrollPhysics(), //禁止拖到效果
                        children: <Widget>[
                          GestureDetector(
                            onTap: () {
                              _getImage();
                            },
                            child: Container(
                              height: 80.0,
                              padding: EdgeInsets.only(left: 15.0, right: 10.0),
                              color: Color(0xFFFFFFFF),
                              margin: EdgeInsets.only(top: 15.0),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Container(
                                    child: Text("头像",
                                        style: new TextStyle(
                                          color: Color(0xFF3C4450),
                                          fontSize: 14.0,
                                          decoration: TextDecoration.none,
                                        ),
                                        textAlign: TextAlign.left),
                                  ),
                                  Row(
                                    children: <Widget>[
                                      new CircleAvatar(
                                        backgroundImage:
                                            CachedNetworkImageProvider(
                                          petInfoEntity.data.header,
                                        ),
                                        radius: 30.0,
                                      ),
                                      Icon(
                                        Icons.chevron_right,
                                        color: Color(0xFFB4BEC6),
                                      )
                                    ],
                                  )
                                ],
                              ),
                            ),
                          ),
                          GestureDetector(
                              onTap: () {
                                _editNick();
                              },
                              child: Column(
                                children: <Widget>[
                                  Container(
                                    height: 60.0,
                                    color: Color(0xFFFFFFFF),
                                    padding: EdgeInsets.only(
                                        left: 15.0, right: 10.0),
                                    margin: EdgeInsets.only(top: 15.0),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: <Widget>[
                                        Container(
                                          child: Text(
                                            "昵称",
                                            style: new TextStyle(
                                                color: Color(0xFF3C4450),
                                                fontSize: 14.0,
                                                decoration:
                                                    TextDecoration.none),
                                          ),
                                        ),
                                        Row(
                                          children: <Widget>[
                                            Text(
                                              petInfoEntity.data.nick,
                                              style: new TextStyle(
                                                  color: Color(0xFFB4BEC6),
                                                  fontSize: 14.0),
                                            ),
                                            Icon(
                                              Icons.chevron_right,
                                              color: Color(0xFFB4BEC6),
                                            )
                                          ],
                                        )
                                      ],
                                    ),
                                  ),
                                  Container(
                                    height: 1,
                                    color: Color(0x5eDBDBDB),
                                    margin: EdgeInsets.only(left: 15.0),
                                  )
                                ],
                              )),
                          GestureDetector(
                              child: Column(
                            children: <Widget>[
                              Container(
                                height: 60.0,
                                color: Color(0xFFFFFFFF),
                                padding:
                                    EdgeInsets.only(left: 15.0, right: 10.0),
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: <Widget>[
                                    Container(
                                      child: Text(
                                        "品种",
                                        style: new TextStyle(
                                            color: Color(0xFF3C4450),
                                            fontSize: 14.0,
                                            decoration: TextDecoration.none),
                                      ),
                                    ),
                                    Row(
                                      children: <Widget>[
                                        Text(
                                          petInfoEntity.data.categoryName,
                                          style: new TextStyle(
                                              color: Color(0xFFB4BEC6),
                                              fontSize: 14.0),
                                        ),
                                        Icon(
                                          Icons.chevron_right,
                                          color: Colors.transparent,
                                        )
                                      ],
                                    )
                                  ],
                                ),
                              ),
                              Container(
                                height: 1,
                                color: Color(0x5eDBDBDB),
                                margin: EdgeInsets.only(left: 15.0),
                              )
                            ],
                          )),
                          GestureDetector(
                              onTap: () {
                                _showSexPicker();
                              },
                              child: Column(
                                children: <Widget>[
                                  Container(
                                    height: 60.0,
                                    color: Color(0xFFFFFFFF),
                                    padding: EdgeInsets.only(
                                        left: 15.0, right: 10.0),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: <Widget>[
                                        Container(
                                          child: Text(
                                            "性别",
                                            style: new TextStyle(
                                                color: Color(0xFF3C4450),
                                                fontSize: 14.0,
                                                decoration:
                                                    TextDecoration.none),
                                          ),
                                        ),
                                        Row(
                                          children: <Widget>[
                                            Text(
                                              petInfoEntity.data.sex == 1
                                                  ? "GG"
                                                  : "MM",
                                              style: new TextStyle(
                                                  color: Color(0xFFB4BEC6),
                                                  fontSize: 14.0),
                                            ),
                                            Icon(
                                              Icons.chevron_right,
                                              color: Color(0xFFB4BEC6),
                                            )
                                          ],
                                        )
                                      ],
                                    ),
                                  ),
                                  Container(
                                    height: 1,
                                    color: Color(0x5eDBDBDB),
                                    margin: EdgeInsets.only(left: 15.0),
                                  )
                                ],
                              )),
                          GestureDetector(
                            onTap: () {
                              _showDatePicker();
                            },
                              child: Column(
                            children: <Widget>[
                              Container(
                                height: 60.0,
                                color: Color(0xFFFFFFFF),
                                padding:
                                    EdgeInsets.only(left: 15.0, right: 10.0),
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: <Widget>[
                                    Container(
                                      child: Text(
                                        "生日",
                                        style: new TextStyle(
                                            color: Color(0xFF3C4450),
                                            fontSize: 14.0,
                                            decoration: TextDecoration.none),
                                      ),
                                    ),
                                    Row(
                                      children: <Widget>[
                                        Text(
                                          petInfoEntity.data.birthday,
                                          style: new TextStyle(
                                              color: Color(0xFFB4BEC6),
                                              fontSize: 14.0),
                                        ),
                                        Icon(
                                          Icons.chevron_right,
                                          color: Color(0xFFB4BEC6),
                                        )
                                      ],
                                    )
                                  ],
                                ),
                              ),
                              Container(
                                height: 1,
                                color: Color(0x5eDBDBDB),
                                margin: EdgeInsets.only(left: 15.0),
                              )
                            ],
                          )),
                          GestureDetector(
                              child: Column(
                            children: <Widget>[
                              Container(
                                height: 60.0,
                                color: Color(0xFFFFFFFF),
                                padding:
                                    EdgeInsets.only(left: 15.0, right: 10.0),
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: <Widget>[
                                    Container(
                                      child: Text(
                                        "体重",
                                        style: new TextStyle(
                                            color: Color(0xFF3C4450),
                                            fontSize: 14.0,
                                            decoration: TextDecoration.none),
                                      ),
                                    ),
                                    Row(
                                      children: <Widget>[
                                        Text(
                                          petInfoEntity.data.weight.toString() +
                                              "Kg",
                                          style: new TextStyle(
                                              color: Color(0xFFB4BEC6),
                                              fontSize: 14.0),
                                        ),
                                        Icon(
                                          Icons.chevron_right,
                                          color: Color(0xFFB4BEC6),
                                        )
                                      ],
                                    )
                                  ],
                                ),
                              ),
                              Container(
                                height: 1,
                                color: Color(0x5eDBDBDB),
                                margin: EdgeInsets.only(left: 15.0),
                              )
                            ],
                          )),
                          GestureDetector(
                              onTap: () {
                                if (petInfoEntity.data.deviceId != null) {
                                  Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) => PetDevice(
                                              id: petInfoEntity
                                                  .data.deviceId)));
                                } else {
                                  ///TODO 关联设备
                                }
                                //Navigator.of(context).pushNamed(petdevicePath);
                              },
                              child: Column(
                                children: <Widget>[
                                  Container(
                                    height: 60.0,
                                    color: Color(0xFFFFFFFF),
                                    padding: EdgeInsets.only(
                                        left: 15.0, right: 10.0),
                                    margin: EdgeInsets.only(
                                      top: 15.0,
                                    ),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: <Widget>[
                                        Container(
                                          child: Text(
                                            "关联设备",
                                            style: new TextStyle(
                                                color: Color(0xFF3C4450),
                                                fontSize: 14.0,
                                                decoration:
                                                    TextDecoration.none),
                                          ),
                                        ),
                                        Row(
                                          children: <Widget>[
                                            Text(
                                              petInfoEntity.data.bindMsg,
                                              style: new TextStyle(
                                                  color: Color(0xFFB4BEC6),
                                                  fontSize: 14.0),
                                            ),
                                            Icon(
                                              Icons.chevron_right,
                                              color: Color(0xFFB4BEC6),
                                            )
                                          ],
                                        )
                                      ],
                                    ),
                                  ),
                                  Container(
                                    height: 1,
                                    color: Color(0x5eDBDBDB),
                                    margin: EdgeInsets.only(left: 15.0),
                                  )
                                ],
                              )),
                          GestureDetector(
                              child: Column(
                            children: <Widget>[
                              Container(
                                height: 60.0,
                                color: Color(0xFFFFFFFF),
                                padding:
                                    EdgeInsets.only(left: 15.0, right: 10.0),
                                //margin: EdgeInsets.only(top: 15.0,),
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: <Widget>[
                                    Container(
                                      child: Text(
                                        "记录数据",
                                        style: new TextStyle(
                                            color: Color(0xFF3C4450),
                                            fontSize: 14.0,
                                            decoration: TextDecoration.none),
                                      ),
                                    ),
                                    Row(
                                      children: <Widget>[
                                        Text(
                                          "",
                                          style: new TextStyle(
                                              color: Color(0xFFB4BEC6),
                                              fontSize: 14.0),
                                        ),
                                        Icon(
                                          Icons.chevron_right,
                                          color: Color(0xFFB4BEC6),
                                        )
                                      ],
                                    )
                                  ],
                                ),
                              ),
                            ],
                          )),
                        ],
                      ),
                    ),
                  ),
                  GestureDetector(
                    child: Stack(
                      children: <Widget>[
                        Positioned(
                          child: Container(
                            padding: EdgeInsets.only(bottom: 15.0),
                            height: 65.0,
                            width: double.infinity,
                            alignment: Alignment.center,
                            color: Colors.white,
                            child: Text(
                              "删除宠物信息",
                              style: TextStyle(
                                  fontSize: 14.0, color: Color(0xFFFF5C64)),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
  }

  Future _getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    FileUtils.getInstance().uploadFile(image, (data) {
      Map<String, dynamic> dataMap = json.decode(data);
      if (dataMap["code"] == 200) {
        // _imgs.add(dataMap["data"]);
        // setState(() {
        //   _image = dataMap["data"];
        //   complated1 = image != null && controller.text.length > 0;
        // });
        petInfoEntity.data.header = dataMap["data"];
        _save(FormData.from({"header": dataMap["data"]}));
      }

      // print(data);
    });
  }

  ///通知主页面更新用户信息
  _updateEvent() {
    eventBus.emit(UpdateUser);
  }

  ///保存宠物信息
  _save(FormData data) {
    saveAnimal(petInfoEntity.data.animalId.toString(), data)
        .listen((SuccessEntity data) {
      if (data.code == 200) {
        ///通知主页面更新用户信息
        _updateEvent();
        setState(() {});
      }
    });
  }

  ///修改昵称
  _editNick() async {
    var nick = await Navigator.push(
        context, MaterialPageRoute(builder: (context) => AnimNick()));
    if (petInfoEntity.data.nick != nick) {
      petInfoEntity.data.nick = nick;
      _save(FormData.from({"nick": nick}));
    }
  }

  ///显示性别
  _showSexPicker() {
    Picker(
        confirmText: "确认",
        cancelText: "取消",
        adapter: PickerDataAdapter<String>(pickerdata: SEXS),
        changeToFirst: true,
        hideHeader: false,
        onConfirm: (Picker picker, List value) {
          // print(value.toString());
          // print(picker.adapter.text);
          setState(() {
            // sex = (value[0] + 1).toString();
            // _sex = SEXS[value[0]];
            //  complated4 = sex!="" &&
            if (petInfoEntity.data.sex != value[0] + 1) {
              petInfoEntity.data.sex = value[0] + 1;

              _save(FormData.from({"sex": value[0] + 1}));
            }
          });
        }).show(_scaffoldKey.currentState);
  }


  /// Display date picker.
  void _showDatePicker() {
    DatePicker.showDatePicker(
      context,
      pickerTheme: DateTimePickerTheme(
        // showTitle: _showTitle,
        confirm: Text(
          '确认',
          style: TextStyle(color: Colors.cyan),
        ),
        cancel: Text(
          '取消',
          style: TextStyle(color: Colors.red),
        ),
      ),
      locale: DateTimePickerLocale.zh_cn,
      // minDateTime: DateTime.parse(MIN_DATETIME),
      // maxDateTime: DateTime.parse(MAX_DATETIME),
      // initialDateTime: _dateTime,
      dateFormat: _format,
      // locale: _locale,
      onConfirm: (dateTime, List<int> index) {
        // var time = dateTime.microsecondsSinceEpoch/1000;
        var time = dateTime.millisecondsSinceEpoch~/1000;
        petInfoEntity.data.birthday = dateTime.year.toString() + "-" + dateTime.month.toString() + "-" + dateTime.day.toString();
        _save(FormData.from({"birthday": time}));
        // print(time);
        // }
        //print();
      },
    );
  }
}
